package com.zhj.process.config;

import com.zhj.process.util.StringUtils;

import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

/**
 * 统一异常拦截
 */
@RestControllerAdvice
public class GlobalExceptionAdvice {

    /**
     * 截取 . 出现的第三次位置
     */
    private final static String PACKAGE_NAME = StringUtils.subStringBeforeNthOccurrence(
        GlobalExceptionAdvice.class.getPackage().getName(),
        '.',
        3);

    /**
     * Handler
     *
     * @param exception exception
     * @return the result
     * @since 1.0.0
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<String> handlerException(RuntimeException exception) {
        exception.printStackTrace();
        return Result.fail("系统运行异常:" + exception.getMessage());
    }

    /**
     * 拦截系统空指针的异常
     *
     * @param exception exception
     * @return the result
     */
    @ExceptionHandler(NullPointerException.class)
    public Result<String> handlerException(NullPointerException exception) {
        exception.printStackTrace();
        StackTraceElement[] stackTrace = exception.getStackTrace();
        String location = stackTrace[0].toString();
        //替换自己的敏感包名
        if (location.startsWith(PACKAGE_NAME)) {
            location = location.replace(PACKAGE_NAME, "server.package");
        }
        return Result.fail("系统空指针异常:" + location);
    }

    /**
     * 拦截参数
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handlerException(MethodArgumentNotValidException exception) {
        exception.printStackTrace();
        BindingResult result = exception.getBindingResult();
        String msg =
            result.getFieldErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining(","));
        return Result.fail("参数校验异常:" + msg);
    }

    /**
     * Handler exception
     *
     * @param exception exception
     * @return the result
     * @since 1.0.0
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public Result<String> handlerException(IllegalArgumentException exception) {
        exception.printStackTrace();
        return Result.fail("非法的参数异常");
    }

    /**
     * Handler exception
     *
     * @param exception exception
     * @return the result
     * @since 1.0.0
     */
    @ExceptionHandler(Exception.class)
    public Result<String> handlerException(Exception exception) {
        exception.printStackTrace();
        return Result.fail("系统异常请联系管理员");
    }

}
